package com.ruoyi.squadweb.utils;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.squadweb.vo.PlayerNewVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PlayerResolverHttpUtils {
    private static final Logger log = LoggerFactory.getLogger(PlayerResolverHttpUtils.class);
    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType 编码类型
     * @return 所代表远程资源的响应结果
     */
    public static List<String> sendGet(String url, String param, String contentType)
    {
        StringBuilder result = new StringBuilder();
        List<String> listPlayer = new ArrayList<>();
        BufferedReader in = null;
        try
        {
            String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null)
            {
                listPlayer.add(line);
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (in != null)
                {
                    in.close();
                }
            }
            catch (Exception ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return listPlayer;
    }


    public static List<PlayerNewVO> playerResolver(List<String> dataList) {
        // 定义线程池配置
        int corePoolSize = 4; // 根据实际情况调整核心线程数
        int maxPoolSize = 8; // 根据实际情况调整最大线程数
        long keepAliveTime = 60L; // 空闲线程存活时间（秒）
        TimeUnit timeUnit = TimeUnit.SECONDS; // 时间单位

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                timeUnit,
                new LinkedBlockingQueue<>());

        List<Future<PlayerNewVO>> futures = new ArrayList<>();
        List<PlayerNewVO> playerNewVOS = new ArrayList<>();
        try {
            for (String data : dataList) {
                PlayerNewVO playerNewVO = processPlayerData(data);
                if (playerNewVO != null) {
                    playerNewVOS.add(playerNewVO); // 获取并添加结果，可能会阻塞直到结果可用
                }
//                Future<PlayerNewVO> future = executor.submit(() -> processPlayerData(data));
//                futures.add(future);
            }
//            for (Future<PlayerNewVO> future : futures) {
//                PlayerNewVO playerNewVO = future.get();
//                if (playerNewVO != null) {
//                    playerNewVOS.add(playerNewVO); // 获取并添加结果，可能会阻塞直到结果可用
//                }
//            }

//        } catch (InterruptedException | ExecutionException e) {
//            e.printStackTrace();
        } finally {
            // 关闭线程池
            executor.shutdown();
        }

        return playerNewVOS;
    }

    private static PlayerNewVO processPlayerData(String data) {
        Pattern pattern = Pattern.compile("(ID:\\s*(\\d+))\\s*\\|\\s*(Online\\s*IDs:\\s*(.*?))\\s*\\|\\s*(Name:\\s*(.*?))\\s*\\|\\s*(Team\\s*ID:\\s*(\\d+))\\s*\\|\\s*(Squad\\s*ID:\\s*(.*))\\s*\\|\\s*(Is\\s*Leader:\\s*(True|False))\\s*\\|\\s*(Role:\\s*(.*))");
        Matcher matcher = pattern.matcher(data);
        if (matcher.matches()) {
            List<String> ids = new ArrayList<>();
            String eosId = matcher.group(4).replace("EOS:", "").trim();
            String steamId = matcher.group(4).split(" steam: ")[1].trim();
            ids.add("EOS " + eosId);
            ids.add(steamId);

            PlayerNewVO playerNewVO = new PlayerNewVO(
                    Integer.parseInt(matcher.group(2)),
                    ids,
                    matcher.group(6),
                    Integer.parseInt(matcher.group(8)),
                    matcher.group(10),
                    matcher.group(12),
                    matcher.group(14)
            );
            return playerNewVO;
        }
        return null;
    }
}
